package com.zhenwei.zscm.repo;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhenwei.zscm.common.base.BaseEntity;
import com.zhenwei.zscm.common.base.MybatisWrapper;
import com.zhenwei.zscm.common.utils.Linq;
import com.zhenwei.zscm.model.dto.user.UserDTO;
import com.zhenwei.zscm.entity.UserEntity;
import com.zhenwei.zscm.mapper.IUserMapper;
import com.zhenwei.zscm.mappings.UserMapping;
import com.zhenwei.zscm.model.enums.RoleEnum;
import com.zhenwei.zscm.model.vo.user.QueryUserVO;
import com.zhenwei.zscm.model.vo.user.UserVO;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserRepo extends ServiceImpl<IUserMapper, UserEntity> {

    public UserDTO getUser(String userName, String password) {
        var qw = new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getUserName, userName)
                .eq(UserEntity::getPassword, password)
                .eq(UserEntity::getDeleted, false);
        UserEntity user = Linq.getFirst(this.list(qw));
        if(user == null){
            return null;
        }
        return UserMapping.INSTANCE.entity2dto(user);
    }
    public UserDTO getUserById(String userId){
        var qw = new LambdaQueryWrapper<UserEntity>()
                .eq(UserEntity::getGuid, userId)
                .eq(BaseEntity::getDeleted, false);
        UserEntity user = Linq.getFirst(this.list(qw));
        if(user == null){
            return null;
        }
        return UserMapping.INSTANCE.entity2dto(user);
    }

    /**
     * 添加用户
     * @param vo 用户表单
     * @return UserDTO
     */
    public UserDTO createUser(UserVO vo) {
        vo.setGuid(IdUtil.simpleUUID());
        var entity = UserMapping.INSTANCE.vo2Entity(vo);
        if(this.save(entity)){
            return UserMapping.INSTANCE.entity2dto(entity);
        }
        return null;
    }

    /**
     * 查询用户列表
     * @param vo 查询参数
     * @return 用户列表
     */
    public List<UserDTO> getUserPageList(QueryUserVO vo) {
        var qw = new LambdaQueryWrapper<UserEntity>();
        qw.eq(UserEntity::getDeleted, false);
        qw.eq(StrUtil.isNotBlank(vo.getRole()), UserEntity::getRole, vo.getRole());
        qw.like(StrUtil.isNotBlank(vo.getUserName()), UserEntity::getUserName, vo.getUserName());
        qw.like(StrUtil.isNotBlank(vo.getRealName()), UserEntity::getRealName, vo.getRealName());
        qw.orderByDesc(UserEntity::getId);
        var p = new Page<UserEntity>(vo.getPageNo(), vo.getPageSize(),true);
        Page<UserEntity> page = this.page(p, qw);
        List<UserEntity> list = page.getRecords();
        vo.setTotalCount(page.getTotal());
        return Linq.mapList(list, UserMapping.INSTANCE::entity2dto);
    }

    /**
     * 只更新用户信息，密码不更新
     * @param vo 用户信息
     * @return bool
     */
    public boolean updateUser(UserVO vo){
        var u = new LambdaUpdateWrapper<UserEntity>();
        u.eq(UserEntity::getGuid, vo.getGuid());
        u.eq(BaseEntity::getDeleted, false);
        u.set(UserEntity::getRealName, vo.getRealName());
        u.set(UserEntity::getUserName, vo.getUserName());
        u.set(UserEntity::getRole, vo.getRole());
        u.set(UserEntity::getRoleName, vo.getRoleName());
        MybatisWrapper.fillUser(u);
        return this.update(u);
    }

    /**
     * 更新用户密码
     * @param vo 用户信息
     * @return bool
     */
    public boolean updateUserPwd(UserVO vo) {
        var u = new LambdaUpdateWrapper<UserEntity>();
        u.eq(UserEntity::getGuid, vo.getGuid());
        u.eq(BaseEntity::getDeleted, false);
        u.set(UserEntity::getPassword, vo.getPassword());
        MybatisWrapper.fillUser(u);
        return this.update(u);
    }

    /**
     * 检查用户登录名是否存在
     * @param userName 登录名
     * @return bool
     */
    public boolean checkUserNameExists(String userName, String userId) {
        var q = new LambdaQueryWrapper<UserEntity>()
                .eq(UserEntity::getUserName, userName)
                .ne(StrUtil.isNotBlank(userId), UserEntity::getGuid, userId)
                .eq(UserEntity::getDeleted, false);
        return this.exists(q);
    }

    /**
     * 删除一个未删除的用户
     * @param userId 用户id
     * @return bool
     */
    public boolean delete(String userId) {
        var u = new LambdaUpdateWrapper<UserEntity>()
                .eq(UserEntity::getGuid, userId)
                .ne(UserEntity::getRole, RoleEnum.ADMIN.name())
                .eq(UserEntity::getDeleted, false)
                .set(UserEntity::getDeleted, true);
        MybatisWrapper.fillUser(u);
        return this.update(u);
    }

    /**
     * 检查是否存在指定角色的用户
     * @param oldRole 角色编码
     * @return bool
     */
    public boolean checkExistsRoleUser(String oldRole) {
        var q = new LambdaQueryWrapper<UserEntity>()
                .eq(UserEntity::getRole, oldRole)
                .eq(UserEntity::getDeleted, false);
        return this.exists(q);
    }

    /**
     * 旧角色删除后，修改用户角色为普通用户
     * @param oldRole 旧角色
     * @return bool
     */
    public boolean updateUserRoleToNormalUser(String oldRole) {
        var u = new LambdaUpdateWrapper<UserEntity>()
                .eq(UserEntity::getRole, oldRole)
                .eq(UserEntity::getDeleted, false)
                .set(UserEntity::getRole, RoleEnum.USER.name())
                .set(UserEntity::getRoleName, RoleEnum.USER.getText());
        return this.update(u);
    }

    public UserDTO getUserByName(String realName) {
        var q = new LambdaQueryWrapper<UserEntity>()
                .eq(UserEntity::getRealName, realName)
                .eq(UserEntity::getDeleted, false);
        UserEntity user = Linq.getFirst(this.list(q));
        return UserMapping.INSTANCE.entity2dto(user);
    }
}
